import React, { useState } from 'react';

type AuthImageProps = {
    src: string;
    alt: string;
    className?: string;
    headers?: Record<string, string>;
    fallbackSrc?: string;
    width?: number;
    height?: number;
}

const AuthImage = ({
    src,
    alt,
    className = '',
    headers = {},
    fallbackSrc = '/placeholder.png',
    width,
    height
}: AuthImageProps) => {
    const [imgSrc, setImgSrc] = useState(src);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);

    // Convert image URL to blob with auth headers
    const loadImageWithAuth = async () => {
        try {
            const response = await fetch(src, {
                headers: {
                    ...headers,
                    // Add any default headers here
                    'Cache-Control': 'no-cache',
                },
            });

            if (!response.ok) {
                throw new Error('Failed to load image');
            }

            const blob = await response.blob();
            const objectUrl = URL.createObjectURL(blob);
            setImgSrc(objectUrl);
            setLoading(false);
            setError(false);

            // Clean up object URL when component unmounts
            return () => URL.revokeObjectURL(objectUrl);
        } catch (err) {
            console.error('Error loading image:', err);
            setImgSrc(fallbackSrc);
            setLoading(false);
            setError(true);
        }
    };

    React.useEffect(() => {
        loadImageWithAuth().then(cleanup => {
            if (cleanup) {
                return () => cleanup();
            }
        });
    }, [src, JSON.stringify(headers)]);

    if (loading) {
        return <div className={`animate-pulse bg-gray-200 ${className}`} style={{ width, height }} />;
    }

    return (
        <img
            src={imgSrc}
            alt={alt}
            className={`${className} ${error ? 'opacity-50' : ''}`}
            width={width}
            height={height}
            onError={() => {
                setImgSrc(fallbackSrc);
                setError(true);
            }}
        />
    );
};

export default AuthImage;